package com.dg.lecheng.base.core.utils;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/15 0015.
 */
public class FileUtils {

    public static final String FILE_TRAINRECORD_PATH = "D:\\dev\\file\\trainRecord";

    public static final String FILE_UPLOAD_PATH = "D:\\dev\\file";
    public static final String FILE_SERVER_PATH = "\\img";


    /**
     * 导出EXCEL
     *
     * @param workbook
     * @param codedFileName
     */
    public static void exportFile(HSSFWorkbook workbook, String codedFileName, HttpServletResponse response) {
        OutputStream fOut = null;
        try {
            // 生成提示信息，
            response.setContentType("application/vnd.ms-excel");
            // 进行转码，使其支持中文文件名
            codedFileName = java.net.URLEncoder.encode(
                    codedFileName + DateUtil.TimeToForDay(DateUtil.getSystemTime()), "UTF-8");
            response.setHeader("content-disposition", "attachment;filename="
                    + codedFileName + ".xls");

            fOut = response.getOutputStream();
            workbook.write(fOut);
        } catch (UnsupportedEncodingException e1) {
        } catch (Exception e) {
        } finally {
            try {
                if (fOut != null) {
                    fOut.flush();
                    fOut.close();
                }
                if (workbook != null) {
                    workbook.close();
                }
            } catch (IOException e) {
            }
        }
    }

    /**
     * 构造EXCEL内容
     * @param rowNo 行号
     * @param cellMap 列号：内容
     * @return
     */
    public static HSSFWorkbook buildExcelContent(int rowNo , Map<Integer,String> cellMap , List<Map<Integer,String>> contentList){
        // 产生工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 产生工作表对象
        HSSFSheet sheet = workbook.createSheet();
        // 创建第rowNo行
        HSSFRow row = sheet.createRow(rowNo-1);

        HSSFCell cell;
        for(Map.Entry entry : cellMap.entrySet()){
            cell = row.createCell((int)entry.getKey()-1);// 创建第2列
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue((String)entry.getValue());
        }

        for(Map<Integer,String> map : contentList){

            HSSFRow contentRow = sheet.createRow(rowNo);
            for(Map.Entry entry : map.entrySet()){
                cell = contentRow.createCell((int)entry.getKey()-1);// 创建列
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                cell.setCellValue((String)entry.getValue());
            }
            rowNo++;
        }
        return workbook;
    }


    /**
     * 构造EXCEL内容
     * @param rowNo 行号
     * @param cellMap 列号：内容
     * @return
     */
    public static HSSFWorkbook buildExcel(int rowNo , Map<Integer,String> cellMap , List<Map<Integer,String>> contentList,List<Integer> NumericIndexs){
        // 产生工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 产生工作表对象
        HSSFSheet sheet = workbook.createSheet();
        // 创建第rowNo行
        HSSFRow row = sheet.createRow(rowNo-1);

        //列数
        int index = cellMap == null?0:cellMap.size();

        CellStyle style = workbook.createCellStyle();
        // 设置为文本格式，防止变成科学计数法
        DataFormat format = workbook.createDataFormat();


        HSSFCell cell;
        for(Map.Entry entry : cellMap.entrySet()){
            cell = row.createCell((int)entry.getKey()-1);// 创建第2列
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue((String)entry.getValue());
        }

        for(int i = 0;i<200;i++){
            Map<Integer,String> map = null;
            if(null != contentList && contentList.size() > 0 && i<contentList.size()){
                map = contentList.get(i);
            }
            HSSFRow contentRow = sheet.createRow(rowNo);
            for(int j=0;j<index;j++){
                cell = contentRow.createCell(j);// 创建单元格
                if(NumericIndexs.contains(j)){ //数值
                    style.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));//保留两位小数点
                }else{//文本
                    style.setDataFormat(format.getFormat("@"));
                    cell.setCellStyle(style);
                }
                if(null != map && j < map.size()){
                    cell.setCellValue(map.get(j).toString());
                }
            }
            rowNo++;
        }
        return workbook;
    }


    /**
     * 输出信息
     */
    public static void outMessage(String message, HttpServletResponse response) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(message);
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 从文件读取工作簿
     */
    public static Workbook getWorkBook(MultipartFile file) throws Exception {
        Workbook work = null;
        try {
            String fileName = file.getOriginalFilename();
            if (fileName.toLowerCase().endsWith("xls")) {
                work = new HSSFWorkbook(file.getInputStream());
            } else if (fileName.toLowerCase().endsWith("xlsx")) {
                work = new XSSFWorkbook(file.getInputStream());
            } else {
                throw new Exception("格式不对！");
            }
        } catch (IOException e) {
            throw new Exception("格式不对！");
        }
        return work;
    }


    /**
     * 将MultipartFile转化为file并保存到服务器上的某地
     */
    public static void SaveFileFromInputStream(InputStream stream, String path, String savefile) throws IOException
    {
        FileOutputStream fs=new FileOutputStream( path + "/"+ savefile);
        byte[] buffer =new byte[1024*1024];
        int bytesum = 0;
        int byteread = 0;
        while ((byteread=stream.read(buffer))!=-1) {
            bytesum += byteread;
            fs.write(buffer,0,byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
    }

    /**
     * 删除文件
     * @param path
     * @param fileName
     */
    public static boolean removeFile(String path, String fileName){
        System.err.println("path, fileName:"+path+fileName);
        File targetFile = new File(path, fileName);
        if (targetFile.exists()) {
            targetFile.delete();
        } else {
            return false;
        }
        return true;
    }

}
